package com.nowcoder.community.quartz;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.concurrent.TimeUnit;

/**
 * @author TwfPlayer
 * @date 2023/8/23 13:20
 * @description: 定时任务
 * 清理分享图
 */
@Component
public class ShareImageClearJob{
    
    private static final Logger logger = LoggerFactory.getLogger(ShareImageClearJob.class);

    @Value("${wk.image.storage}")
    private String wkImageStorage;


    // Spring定时任务，每隔4分钟清理一次用户生成的长图（清理1分钟之前创建的图片）
    // 这是每台主机上都要执行的操作，因此就用Spring定时任务线程池
    @Scheduled(initialDelay = 10000, fixedDelay = 4*60*1000)
    public void clearShareImage() {
        logger.info("任务开始:[清理用户分享图]...");
        File dir = new File(wkImageStorage);
        if (dir.listFiles() != null && dir.listFiles().length != 0) {
            for (File file : dir.listFiles()) {
                try {
                    Path path = Paths.get(file.getAbsolutePath());
                    FileTime creationTime = Files.readAttributes(path, BasicFileAttributes.class).creationTime();
                    if (System.currentTimeMillis() - creationTime.toMillis() >= 60 * 1000) {
                        file.delete();
                        logger.info(String.format("[删除成功] 文件[%s]已删除！", file.getName()));
                    }
                } catch (IOException e) {
                    logger.error(String.format("[删除失败] 文件[%s]删除失败！", file.getName()));
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }
            }
        }else{

        }
        logger.info("任务完成:[用户分享图清理完成]！");
    }

}
